import 'package:flutter/material.dart';

///INTRODUCE:图片控件
class YJImage extends StatelessWidget {
  final String imagePath; //图片地址
  final double? height; //图片高
  final double? width; //图片宽
  final String? placeholderImage; //占位图
  final String? errorImage; //错误图
  final BoxFit? fit; //图片拉伸方式
  final bool? isClipOval; //是否是圆形
  final double? imageRadius; //设置图片圆角

  const YJImage(
    this.imagePath, {
    Key? key,
    this.height,
    this.width,
    this.placeholderImage,
    this.errorImage,
    this.fit,
    this.isClipOval,
    this.imageRadius,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return buildLoad(context);
  }

  /// 不需要占位图
  Widget buildLoad(BuildContext context) {
    if (placeholderImage == null) {
      return getEndWidget(getImage());
    } else {
      return getEndWidget(getFadeInImage());
    }
  }

  /// 返回最终的Widget
  Widget getEndWidget(widget) {
    //设置图片为圆形
    if (isClipOval == true) {
      return ClipOval(child: widget);
    }
    //设置图片圆角
    if (imageRadius != null) {
      return ClipRRect(
          borderRadius: BorderRadius.circular(imageRadius!), child: widget);
    }
    return widget;
  }

  /// 有占位图组件
  Widget getFadeInImage() {
    return FadeInImage(
        width: width,
        height: height,
        fit: fit ?? BoxFit.contain,
        placeholderFit: fit ?? BoxFit.contain,
        placeholder: getPlaceholder(),
        image: getImageProvider(),
        placeholderErrorBuilder: (ctx, err, stackTrace) => _imagePlaceholder(),
        imageErrorBuilder: (ctx, err, stackTrace) => _imageError());
  }

  /// 无占位图组件
  Widget getImage() {
    return Image(
        image: getImageProvider(),
        width: width,
        height: height,
        fit: fit,
        errorBuilder: (ctx, err, stackTrace) => _imageError());
  }

  /// 占位图错误组件
  Widget _imagePlaceholder() {
    return Image.asset("",
        fit: fit ?? BoxFit.contain, width: width, height: height);
  }

  /// 错误组件
  Widget _imageError() {
    var imagePath = "";
    if (errorImage != null) {
      imagePath = errorImage!;
    }
    return Image.asset(imagePath,
        fit: fit ?? BoxFit.contain, width: width, height: height);
  }

  /// 判断图片是网络还是本地还是应用内
  ImageProvider getImageProvider() {
    if (imagePath.contains("http")) {
      return NetworkImage(imagePath);
    } else {
      return AssetImage(imagePath);
    }
  }

  /// 占位图
  ImageProvider getPlaceholder() {
    return AssetImage(placeholderImage!);
  }
}
